// 防抖函数
// let timer = null;
// export function debounce (fn, delay, ...args) {
// 	if (typeof fn !== 'function') {
//     throw new TypeError('必须传入一个函数作为参数')
//   }
//   timer && clearTimeout(timer)

//   timer = setTimeout(() => {
//     fn(...args)
//   }, delay)
// }
// let timeout = null
let temp;
export function debounce (fn, delay, ...nums) {
	return (function () {
		if(temp) clearTimeout(temp);
		temp = setTimeout(() => {
			//e是事件处理函数都有的一个参数，nums是个数组，在用call的时候需要解构一下
			fn.call(this, ...nums)
			//当然这里也可以用apply但是要麻烦很多因为nums是数组，但还有个e
		}, delay);
	})()
}
// 防抖
export function _debounce(fn, delay = 200) {
  let timer;
  return function () {
    let th = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}

// 节流
export function _throttle(fn, interval = 200) {
  let last;
  let timer;
  return function () {
    let th = this;
    let args = arguments;
    let now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        fn.apply(th, args);
      }, interval);
    } else {
      last = now;
      fn.apply(th, args);
    }
  }
}

export function simpleDebounce(fn, wait) {
  let timer = null
  // 使用到闭包可以访问外部变量
  return () => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(fn, wait);
  }
}

export function simpleThrottle(fn, wait) {
  let timer = null
  // 使用到闭包可以访问外部变量
  return () => {
    if (!timer) {
      timer = setTimeout(() => {
        fn()
        timer = null
      }, wait);
    }
  }
}

export function observerDomResize(dom, callback) {
  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
  const observer = new MutationObserver(callback)
  observer.observe(dom, {attributes: true, attributeFilter: ['style'], attributeOldValue: true})
  return observer;
}